(function(){
  'use strict';

  if (!window.Api) return;
  
  // 获取交易所显示名称（中文（英文）格式）
  function getExchangeDisplayName(connector) {
    var exchanges = {
      'gate_io': '芝麻开门 (Gate.io)',
      'gate_io_perpetual': '芝麻开门合约 (Gate.io Perpetual)',
      'binance': '币安 (Binance)',
      'binance_perpetual': '币安合约 (Binance Perpetual)',
      'binance_us': '币安美国 (Binance US)',
      'okx': '欧易 (OKX)',
      'okx_perpetual': '欧易合约 (OKX Perpetual)',
      'huobi': '火币 (Huobi)',
      'htx': '火币HTX (HTX)',
      'huobi_perpetual': '火币合约 (Huobi Perpetual)',
      'bybit': 'Bybit',
      'bybit_perpetual': 'Bybit合约 (Bybit Perpetual)',
      'kraken': '海妖 (Kraken)',
      'kraken_perpetual': '海妖合约 (Kraken Perpetual)',
      'coinbase': 'Coinbase',
      'coinbase_perpetual': 'Coinbase合约 (Coinbase Perpetual)',
      'kucoin': '库币 (KuCoin)',
      'kucoin_perpetual': '库币合约 (KuCoin Perpetual)',
      'mexc': '抹茶 (MEXC)',
      'bingx': '必应 (BingX)',
      'bing_x': '必应 (BingX)',
      'bitmart': '比特玛特 (BitMart)',
      'bitget': 'Bitget',
      'ascendex': 'AscendEX',
      'ascend_ex': 'AscendEX',
      'crypto_com': 'Crypto.com',
      'vertex': 'Vertex',
      'injective': 'Injective',
      'hyperliquid': 'Hyperliquid'
    };
    return exchanges[connector] || connector;
  }
  
  // 获取市场类型显示名称（中文格式）
  function getMarketDisplayName(marketType) {
    var markets = {
      'spot': '现货',
      'perpetual': '合约',
      'futures': '期货',
      'margin': '杠杆',
      'options': '期权',
      'derivatives': '衍生品'
    };
    return markets[marketType] || marketType;
  }

  var entry = document.getElementById('subs-mgr-entry');
  var openBtn = document.getElementById('btn-open-subs-mgr');
  var view = document.getElementById('subs-mgr-view');
  var backBtn = document.getElementById('btn-subs-back');
  var pauseAllBtn = document.getElementById('btn-subs-pause-all');
  var resumeAllBtn = document.getElementById('btn-subs-resume-all');
  var listWrap = document.getElementById('subs-list');
  var editModal = document.getElementById('subs-edit-modal');
  var editFormWrap = document.getElementById('subs-edit-form');
  var editTitle = document.getElementById('subs-edit-title');

  function show(el, yes){ if (!el) return; el.classList.toggle('is-hidden', !yes); el.style.display = yes ? '' : el.style.display; }

  function isAuthed(){ return !!(window.Auth && window.Auth.getToken && window.Auth.getToken()); }

  async function initVisibility(){ if (entry) entry.style.display = isAuthed() ? '' : 'none'; }

  function field(label, id, opts){ var f=document.createElement('div'); f.className='field'; var l=document.createElement('label'); l.setAttribute('for',id); l.textContent=label; var el; if(opts&&opts.type==='select'){ el=document.createElement('select'); el.className='input'; } else { el=document.createElement('input'); el.className='input'; if(opts&&opts.placeholder) el.placeholder=opts.placeholder; if(opts&&opts.type) el.type=opts.type; } el.id=id; f.appendChild(l); f.appendChild(el); return {wrap:f,input:el}; }

  async function loadConnectorsForSelect(select, marketType){
    try { var path = '/users/connectors' + (marketType ? ('?market_type=' + encodeURIComponent(marketType)) : ''); var data = await window.Api.jsonOrThrow(await window.Api.request('GET', path, null, true)); var cs = (data && data.connectors) || (Array.isArray(data) ? data : []); select.innerHTML=''; for (var i=0;i<cs.length;i++){ var o=document.createElement('option'); o.value=cs[i]; o.textContent=cs[i]; select.appendChild(o); } } catch (_) { select.innerHTML=''; var o=document.createElement('option'); o.textContent='加载失败'; select.appendChild(o); }
  }

  function renderList(items){
    listWrap.innerHTML = '';
    if (!items || !items.length){ listWrap.innerHTML = '<p class="muted">暂无订阅</p>'; return; }
    for (var i=0;i<items.length;i++){
      (function(sub){
        var card = document.createElement('section'); card.className='card';
        var head = document.createElement('div'); head.style.display='flex'; head.style.justifyContent='space-between'; head.style.alignItems='center';
        var title = document.createElement('div'); 
        title.textContent = (sub.script_name || sub.script_code || ('ID ' + sub.script_id));
        console.log('订阅管理: 策略名称:', title.textContent);
        var actions = document.createElement('div'); actions.style.display='flex'; actions.style.gap='8px';
        var btnToggle = document.createElement('button'); btnToggle.className='btn'; btnToggle.textContent = sub.enabled ? '暂停' : '恢复';
        var btnEdit = document.createElement('button'); btnEdit.className='btn'; btnEdit.textContent='编辑';
        var btnDelete = document.createElement('button'); btnDelete.className='btn'; btnDelete.textContent='退出';
        btnDelete.style.backgroundColor = '#dc3545'; btnDelete.style.color = 'white'; btnDelete.style.border = 'none';
        actions.appendChild(btnToggle); actions.appendChild(btnEdit); actions.appendChild(btnDelete);
        head.appendChild(title); head.appendChild(actions); card.appendChild(head);

        var body = document.createElement('div'); body.style.marginTop='8px';
        var exchangeDisplayName = getExchangeDisplayName(sub.connector_name || '');
        var marketDisplayName = getMarketDisplayName(sub.market_type || '');
        body.innerHTML = '<div class="small muted">交易所: ' + exchangeDisplayName + ' · 比例: ' + (sub.allocation && sub.allocation.value || '-') + '% · 市场: ' + marketDisplayName + '</div>';
        console.log('订阅管理: 交易所显示:', exchangeDisplayName);
        card.appendChild(body);

        btnToggle.addEventListener('click', async function(){ try{ var path = '/subscriptions/' + sub.script_id + (sub.enabled ? '/pause' : '/resume'); await window.Api.jsonOrThrow(await window.Api.request('POST', path, {}, true)); loadList(); }catch(_){ } });
        btnEdit.addEventListener('click', function(){ openEdit(sub); });
        btnDelete.addEventListener('click', async function(){
          if (confirm('确定要退出此订阅吗？此操作不可撤销。')) {
            try {
              console.log('订阅管理: 删除订阅', sub.script_id);
              await window.Api.jsonOrThrow(await window.Api.request('DELETE', '/subscriptions/' + sub.script_id, {}, true));
              console.log('订阅管理: 订阅删除成功');
              loadList();
            } catch (err) {
              console.error('订阅管理: 删除订阅失败:', err);
              alert('删除订阅失败: ' + (err && err.message ? err.message : '未知错误'));
            }
          }
        });

        listWrap.appendChild(card);
      })(items[i]);
    }
  }

  async function loadList(){ 
    if (!listWrap) {
      console.log('订阅管理: 未找到列表容器');
      return;
    }
    
    listWrap.innerHTML = '<p class="muted">加载中...</p>'; 
    try{ 
      console.log('订阅管理: 开始加载订阅列表...');
      console.log('订阅管理: 发送GET请求到 /subscriptions');
      
      var data = await window.Api.jsonOrThrow(await window.Api.request('GET','/subscriptions',null,true)); 
      console.log('订阅管理: 原始订阅数据:', data);
      console.log('订阅管理: 数据类型:', typeof data);
      console.log('订阅管理: 数据是否为数组:', Array.isArray(data));
      
      var items = Array.isArray(data) ? data : (data.items||[]);
      console.log('订阅管理: 处理后的订阅数据:', items);
      console.log('订阅管理: 订阅数量:', items.length);
      
      renderList(items); 
    }catch(err){ 
      console.log('订阅管理: 加载失败:', err);
      listWrap.innerHTML = '<p class="muted">加载失败: ' + (err && err.message ? err.message : '未知错误') + '</p>'; 
    } 
  }

  function openEdit(sub){
    editTitle.textContent = '编辑订阅';
    editFormWrap.innerHTML = '';
    var fAlloc = field('投入比例(%)','subs-edit-alloc',{type:'number'});
    var fConn = field('交易所','subs-edit-connector',{type:'select'});
    var fMax = field('单笔上限(可选)','subs-edit-max',{type:'number',placeholder:'如 1000'});
    var fSlip = field('滑点bps(可选)','subs-edit-slip',{type:'number',placeholder:'如 10'});
    var msg = document.createElement('div'); msg.className='form-msg'; msg.id='subs-edit-msg';
    var row = document.createElement('div'); row.style.display='flex'; row.style.gap='8px';
    var btnCancel = document.createElement('button'); btnCancel.className='btn'; btnCancel.type='button'; btnCancel.textContent='取消';
    var btnOk = document.createElement('button'); btnOk.className='btn primary'; btnOk.type='button'; btnOk.textContent='保存';

    editFormWrap.appendChild(fAlloc.wrap); editFormWrap.appendChild(fConn.wrap); editFormWrap.appendChild(fMax.wrap); editFormWrap.appendChild(fSlip.wrap); editFormWrap.appendChild(msg); row.appendChild(btnCancel); row.appendChild(btnOk); editFormWrap.appendChild(row);

    if (sub && sub.allocation && sub.allocation.value != null) fAlloc.input.value = sub.allocation.value;
    if (sub && sub.max_notional != null) fMax.input.value = sub.max_notional;
    if (sub && sub.slippage_bps != null) fSlip.input.value = sub.slippage_bps;
    loadConnectorsForSelect(fConn.input, sub && sub.market_type);
    if (sub && sub.connector_name) fConn.input.value = sub.connector_name;

    function close(){ editModal.classList.add('is-hidden'); }
    btnCancel.addEventListener('click', close);
    editModal.addEventListener('click', function(e){ if (e.target && e.target.getAttribute('data-close')==='modal') close(); });

    btnOk.addEventListener('click', async function(){
      msg.textContent = '提交中...';
      var payload = {};
      var alloc = parseFloat(fAlloc.input.value||''); if (!isNaN(alloc) && alloc>0) payload.allocation = { mode: 'percent_of_equity', value: alloc };
      var conn = fConn.input.value || ''; if (conn) payload.connector_name = conn;
      var maxn = parseFloat(fMax.input.value||''); if (!isNaN(maxn) && maxn>0) payload.max_notional = maxn;
      var slip = parseFloat(fSlip.input.value||''); if (!isNaN(slip) && slip>=0) payload.slippage_bps = slip;
      try{ await window.Api.jsonOrThrow(await window.Api.request('PATCH','/subscriptions/' + sub.script_id, payload, true)); close(); loadList(); }catch(err){ msg.text内容 = '失败：' + (err && err.message ? err.message : '未知错误'); }
    });

    editModal.classList.remove('is-hidden');
  }

  openBtn && openBtn.addEventListener('click', function(){ show(entry,false); show(view,true); loadList(); });
  backBtn && backBtn.addEventListener('click', function(){ show(view,false); show(entry,true); });
  pauseAllBtn && pauseAllBtn.addEventListener('click', async function(){ try{ await window.Api.jsonOrThrow(await window.Api.request('POST','/subscriptions/pause-all',{},true)); loadList(); }catch(_){ } });
  resumeAllBtn && resumeAllBtn.addEventListener('click', async function(){ try{ await window.Api.jsonOrThrow(await window.Api.request('POST','/subscriptions/resume-all',{},true)); loadList(); }catch(_){ } });

  // 暴露loadList函数供外部调用
  window.subscriptionsManager = {
    loadList: loadList
  };

  // 在控制台暴露手动加载函数
  window.manualLoadSubscriptions = loadList;

  // 监听页面切换
  window.addEventListener('hashchange', function() {
    var currentHash = window.location.hash;
    console.log('订阅管理: 页面hash变化:', currentHash);
    
    if (currentHash === '#subscriptions') {
      console.log('订阅管理: 检测到订阅页面，开始加载数据...');
      loadList();
    }
  });

  // 立即检查当前页面状态
  setTimeout(function() {
    var currentHash = window.location.hash;
    console.log('订阅管理: 当前页面hash:', currentHash);
    
    if (currentHash === '#subscriptions') {
      console.log('订阅管理: 检测到订阅页面，开始加载数据...');
      loadList();
    }
  }, 100);

  initVisibility();
})();


